package cn.iocoder.yudao.module.trade.service.order.handler;

import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.promotion.api.combination.dto.CombinationRecordCreateRespDTO;
import cn.iocoder.yudao.module.promotion.api.quickcombination.QuickCombinationApi;
import cn.iocoder.yudao.module.promotion.api.quickcombination.QuickCombinationRecordApi;
import cn.iocoder.yudao.module.trade.convert.order.TradeOrderConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.enums.order.TradeOrderStatusEnum;
import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.ORDER_CREATE_FAIL_EXIST_UNPAID;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.ORDER_DELIVERY_FAIL_COMBINATION_RECORD_STATUS_NOT_SUCCESS;

@Component
public class TradeQuickCombinationOrderHandler implements TradeOrderHandler {

    @Resource
    private QuickCombinationApi quickCombinationApi;

    @Resource
    private QuickCombinationRecordApi quickCombinationRecordApi;

    @Resource
    private MemberUserApi memberUserApi;
    @Override
    public void beforeOrderCreate(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {

        if(!TradeOrderTypeEnum.isQuickCombination(order.getType())){
            return;
        }

        Assert.isTrue(orderItems.size()==1, "促销活动只允许选择一个商品");
        TradeOrderItemDO item = orderItems.get(0);
        quickCombinationApi.validateQuickCombination(order.getUserId(), order.getQuickCombinationActivityId(), item.getSkuId(), item.getCount());
    }

    @Override
    public void afterPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {

        if(!TradeOrderTypeEnum.isQuickCombination(order.getType())){
            return;
        }

        Assert.isTrue(orderItems.size()==1, "促销活动只允许选择一个商品");

        MemberUserRespDTO user = memberUserApi.getUser(order.getUserId());
        Assert.notNull(user);
        quickCombinationRecordApi.createCombinationRecord(TradeOrderConvert.INSTANCE.convert(user, order, orderItems.get(0)));
    }

    @Override
    public void beforeDeliveryOrder(TradeOrderDO order) {
        if(!TradeOrderTypeEnum.isQuickCombination(order.getType())) {
            return;
        }

        //todo 删除redord
    }
}
